/**
 * Created by jiexin on 2017/9/14.
 */
layui.use(['form', 'element', 'layer', 'table', 'ztree', 'upload'], function() {
    var form = layui.form;
    var element = layui.element;
    var table = layui.table;
    var $ = layui.jquery;
    var layer = layui.layer; //弹层
    var upload = layui.upload;
    var ztree = layui.ztree;


    // var yaml_data = [{"yaml_id":"1", "yaml_name":"2", "yaml_describe":"3"},{"yaml_id":"1", "yaml_name":"2", "yaml_describe":"3"}];

    var yss_a = document.getElementById('yss_all');
    var yss_a_h = yss_a.offsetHeight - 90;
    var yss_a_w = yss_a.offsetWidth * 0.56;
    console.log(yss_a_w);


    element.on('tab(yamltab)', function(data){
        if (data.index === 1){
            $.ajax({
                url: "/yaml-read/",
                dataType: 'json',
                type: 'POST',
                async:false,
                success: function (yamldata) {
                    yaml_data = yamldata["yaml_all_list"];
                }
            });
            $('.layui-table').each(function() {
                //获取标签对于的一个属性
                var $obj = $(this);
                var tableid = $obj[0].id;
                var etaleid = '#' + tableid;
                var toolid = 'tool(' + tableid + ')';
                createtable(etaleid,tableid,yaml_data,table_format_yaml, yss_a_h);
                yamltool(toolid,tableid);
                console.log("##########")
            });
        }else if (data.index === 2){
            treeajax()
        }
    });

    var table_format_yaml = [[
         {field: 'yaml_id', align: 'center', title: 'ID', width: "10%"}
         , {field: 'yaml_name', align: 'center', title: 'Yaml名称', width: "22%"}
         , {field: 'yaml_describe', title: '描述', width: "40%"}
         , {fixed: 'right',width: "30%", align: 'center',  title: '操作', toolbar: '#yamlDemo'}
    ]];

    var yamltable;
    function createtable(etaleid,tableid,datas,table_format, theight) {
        yamltable = table.render({
            elem: etaleid,
            id: tableid,
            height: theight,
            width:yss_a_w,
            data: datas,
            cols: table_format
        });
    }

     function yamltool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);

            //tr.index()
            if (layEvent === 'check') {
                var yamljson = yaml_data[tr.index()]["yaml_json"];
                var new_yaml_data;
                var yml;
                try {
                    new_yaml_data = JSON.parse(yamljson)
                } catch (e) {
                    document.getElementById("yamlcheck").value = "convert Error, check your data please.";
                    return;
                }

                yml = YAML.stringify(new_yaml_data,4,4);
                document.getElementById("yamlcheck").value = yml;
            } else if (layEvent === 'del') {
                layer.msg('确定删除这个YAML文件！', {
                    time: 20000,
                    //20s后自动关闭
                    btn: ['确认', '取消'],
                    success: function (layero) {
                        var btn = layero.find('.layui-layer-btn');
                        var btntrue = layero.find('.layui-layer-btn0');
                        btn.css('text-align', 'center');
                        btntrue.on('click', function () {
                            $.ajax({
                                url: "/yaml-del/",
                                dataType: 'json',
                                type: 'POST',
                                data: {"id": data["yaml_id"], "type": "yaml"},
                                success: function (yamldata) {
                                    yaml_data = yamldata["data_list"];
                                    yamltable.reload({
                                         data: yaml_data
                                    });
                                }
                            })
                        })
                    }
                });
            }
        });
    }




    // 焦点判断
    $(":input").focus(function(){
    }).blur(function(){
           $('#tojson').trigger("click")
    });

    form.on('submit(submitde)', function(data){
        console.log(data.field); //当前容器的全部表单字段，名值对形式：{name: value}
        var formdata = data.field;
        $.ajax({
            url: "/yaml-write/",
            dataType: 'json',
            type: 'POST',
            data: {"data": JSON.stringify(formdata)},
            success: function (statusdata) {
                if (statusdata["status"] === 0) {
                    $('#resets').trigger("click");
                    layer.msg('添加成功！')
                }else {
                    layer.msg('添加失败！')
                }
            }
        })
    });



    ////////////////////////////////////////////////////////////////////
    //tree
    ///////////////////////////////////////////////////////////////////

    // $("#yamlrules").on('click', function () {
    //     treeajax()
    // });

    //tree 加载
    function treeajax() {
        $.ajax({
            url: "/ansible-rules/",
            dataType: 'json',
            type: 'POST',
            async: false,
            success: function (yamlruledata) {
                var zNodes = yamlruledata["treedata"];
                console.log('已经获取到数据');
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            }
        })
    }

    var rule_create='<form id="formtree1" name="formtree1" class="layui-form layui-form-pane"><div class="layui-form-item"><label class="layui-form-label" style="color:#000;">类型选择</label><div class="layui-input-inline"><select id="rulelist" name="rulelist" lay-filter="rulelist"><option value=""></option><option value="0" selected="">目录</option><option value="1">文件</option></select></div></div><div class="layui-form-item"><label class="layui-form-label" style="color:#000;">名称配置</label><div class="layui-input-inline"><input id="rulename" type="text" name="perkey" autocomplete="rulename" placeholder="输入名称" required lay-verify="required" class="layui-input"></div></div></form>';
    var file_create='<form id="formtree2" name="formtree2" class="layui-form layui-form-pane"><div class="layui-form-item"><label class="layui-form-label" style="color:#000;">文件名称</label><div class="layui-input-inline"><input id="filename" type="text" name="perkey" autocomplete="filename" placeholder="输入名称" required lay-verify="required" class="layui-input"></div></div></form>';

    $("#createrule").on("click", function () {
        layer.msg(
            content=rule_create,
            {
            time: 200000,
            area: ['360px', '260px'],
            //200s后自动关闭
            btn: ['确定'],
            success: function (layero) {
                var btn = layero.find('.layui-layer-btn');
                form.render('select');
                btn.css('text-align', 'center');
                btn.on('click', function () {
                    console.log($("#rulelist").val(),$("#rulename").val())
                })
            }
        });
    });

    function extra_data(input,data){
        var item=[];
        $.each(data,function(k,v){
            item.push('<input type="hidden" name="'+k+'" value="'+v+'">');
        });
        $(input).after(item.join(''));
    }

    //上传
    var tree_dir_file = "";
    var rule_Count = 1;
    var rules_upload = upload.render({
        elem: '#rulesupload'
        // ,data:{"dir_file":tree_dir_file}
        ,url: '/upload/'
        ,accept: 'file' //普通文件
        ,before:function(input){
            rules_upload.config.data.dir_file=tree_dir_file;
        }
        ,done: function(res){
            if (res["status"] === 0){
                layer.msg("文件添加成功");
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                var nodes = zTree.getSelectedNodes();
                if (nodes.length === 0){
                    layer.msg("请选中文件夹")
                }else{
                    zTree.reAsyncChildNodes(nodes[0], "refresh", false);
                }
                // if (click_treeNode === undefined){
                //     layer.msg("请选中文件夹")
                // }else{
                //     // zTree.addNodes(click_treeNode, {id:(101 + rule_Count), pId:click_treeNode.id, name:res["filename"], status:1});
                //     // rule_Count++
                //
                //     zTree.reAsyncChildNodes(nodes[0], "refresh", false);
                // }
            }else{
                layer.msg("请选择目录")
            }
        }
    });

    var setting = {
        async: {
            enable: true,
            url: "/ansible-rules/",
            dataType: "json",
            dataFilter:filter
        },
        view: {
            addHoverDom: addHoverDom,  //添加及添加按钮的图标
            removeHoverDom: removeHoverDom,  //移除 图标
            selectedMulti: false,
            showTitle: false
        },
        edit: {
            enable: true,
            editNameSelectAll: true,
            showRemoveBtn: showRemoveBtn, //移除按钮图标
            showRenameBtn: showRenameBtn //重命名按钮图标
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeDrag: beforeDrag,
            beforeEditName: beforeEditName, //编辑按钮的 click 事件
            beforeRemove: beforeRemove, //节点被删除之前的事件
            beforeRename: beforeRename, //节点重命名之前的事件
            beforeClick: zTreeBeforeClick,
            onRemove: onRemove, //节点被删除之后的事件
            onRename: onRename, //节点重命名之后的事件
            onClick: zTreeOnClick
        }
    };

    //异步加载过滤
    function filter(treeId, parentNode, responseData) {
        var ajaxData = [];
        console.log(responseData);

        // if (responseData) {
        //     for (var i=0; i < responseData["treedata"].length; i++){
        //         if (responseData["treedata"][i]["pId"] === parentNode.id && responseData["treedata"][i]["name"] === addnodename){
        //             return responseData["treedata"][i]
        //         }
        //     }
        // }

        if (responseData) {
            if (parentNode.id === 1){
                for (var i=0; i < responseData["treedata"].length; i++) {
                    if (responseData["treedata"][i]["pId"] >= parentNode.id){
                        ajaxData.push(responseData["treedata"][i])
                    }
                }
            }else{
                var len_pid =  parentNode.id.toString().length;
                for (var i=0; i < responseData["treedata"].length; i++) {
                    var pid_head = responseData["treedata"][i]["pId"].toString().substring(0,len_pid);
                    if (parseInt(pid_head) === parentNode.id){
                        ajaxData.push(responseData["treedata"][i])
                    }
                }

            }
        }
        console.log(ajaxData);
        return ajaxData

    }

    var log, className = "dark";
    function beforeDrag(treeId, treeNodes) {
        return false;
    }

    function beforeEditName(treeId, treeNode) {
        className = (className === "dark" ? "":"dark");
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        zTree.selectNode(treeNode);
        // setTimeout(function() {
        //     if (confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？")) {
        //         setTimeout(function() {
        //             zTree.editName(treeNode);
        //         }, 0);
        //     }
        // }, 0);

        setTimeout(function() {
            zTree.editName(treeNode);
        }, 0);

        return false;
    }



    function beforeRemove(treeId, treeNode) {
        var returndata = checkAllParents(treeNode, '', treeNode.name);
        className = (className === "dark" ? "" : "dark");
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        // zTree.selectNode(treeNode);
        // var newfile = returndata + '\\' + newName;
        layer.msg("确认删除目录或文件", {
            time: 20000,
            //20s后自动关闭
            btn: ['确认', '取消'],
            success: function (layero) {
                var btn = layero.find('.layui-layer-btn');
                var btntrue = layero.find('.layui-layer-btn0');
                btn.css('text-align', 'center');
                btntrue.on('click', function () {
                    var delfile = returndata + '\\' + treeNode.name;
                    if (modifyfile('del', delfile, 0)){
                        console.log('删除文件名成功');
                        zTree.removeNode(treeNode);
                    }
                });
            }
        });
        return false
    }

    function onRemove(e, treeId, treeNode) {
        showLog("[ "+getTime()+" onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
    }

    function beforeRename(treeId, treeNode, newName, isCancel) {
        // console.log(treeNode);
        var returndata = checkAllParents(treeNode, '', treeNode.name);
        className = (className === "dark" ? "":"dark");

        if (newName.length === 0) {
            setTimeout(function() {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.cancelEditName();
                layer.msg("节点名称不能为空.");
            }, 0);
            return false;
        }
        var oldfile = returndata + '\\' + treeNode.name;
        var newfile = returndata + '\\' + newName;
        console.log(oldfile, newfile);
        if (isCancel === undefined){
            if (modifyfile('move', oldfile, newfile)){
                // return true;
            }
            else {
                setTimeout(function(){
                    var treeObj = $.fn.zTree.getZTreeObj(treeId);
                    treeObj.cancelEditName();
                }, 0);
                return false;
            }
            return true
        }
    }

    function onRename(e, treeId, treeNode, isCancel) {
        showLog((isCancel ? "<span style='color:red'>":"") + "[ "+getTime()+" onRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>":""));
    }

    //是否移除
    function showRemoveBtn(treeId, treeNode) {
        if (treeNode.level !== 0){
            return true

        }else{
            return false
        }
    }

    //是否修改
    function showRenameBtn(treeId, treeNode) {
        if (treeNode.level !== 0){
            return true
        }else{
            return false
        }
    }

    function showLog(str) {
        if (!log) log = $("#log");
        log.append("<li class='"+className+"'>"+str+"</li>");
        if(log.children("li").length > 8) {
            log.get(0).removeChild(log.children("li")[0]);
        }
    }
    function getTime() {
        var now= new Date(),
        h=now.getHours(),
        m=now.getMinutes(),
        s=now.getSeconds(),
        ms=now.getMilliseconds();
        return (h+":"+m+":"+s+ " " +ms);
    }

    //添加
    var newCount = 1;
    var addnodename;
    function addHoverDom(treeId, treeNode) {
        if (treeNode.status === 0){
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                + "' title='添加' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_"+treeNode.tId);
            if (btn) btn.bind("click", function(){
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.selectNode(treeNode);// 使添加的节点处于选中状态
                layer.msg(
                    content=rule_create,
                    {
                    time: 200000,
                    area: ['360px', '260px'],
                    //200s后自动关闭
                    btn: ['确定'],
                    success: function (layero) {
                        var btn = layero.find('.layui-layer-btn');
                        form.render('select');
                        btn.css('text-align', 'center');
                        btn.on('click', function () {
                            var rulestatus = $("#rulelist").val();
                            var rulesfile = $("#rulename").val();
                            if (rulesfile !== ""){
                                //判断添加目录，防止一级目录调用函数异常
                                var returndata = checkAllParents(treeNode, '', treeNode.name);
                                if (returndata !== undefined) {
                                    var add_directory = returndata + '\\' + treeNode.name + '\\' + rulesfile;
                                }else {
                                    var add_directory = treeNode.name + '\\' + rulesfile;
                                }

                                //判断目录下是否存在文件
                                if (treeNode.children === undefined){
                                    var arra = 0
                                }else{
                                    var arra = parseInt(treeNode.children[treeNode.children.length - 1]["id"]) + 1; // 与添加文件同级的最后一个id
                                }
                                var nodes = zTree.getSelectedNodes();
                                nodes[0].isParent = true; //reAsyncChildNodes方法只对节点有isParent属性且为true的时候有效!!!!
                                if (rulestatus == 0){
                                    if (modifyfile('add', add_directory, [arra, treeNode.id, 0].join("|"))){
                                        // zTree.addNodes(treeNode, {id:arra, pId:treeNode.id, name:rulesfile, status:0});
                                        addnodename=rulesfile;
                                        zTree.reAsyncChildNodes(nodes[0], "refresh", false);
                                    }else{
                                        layer.msg('添加失败！！！')
                                    }
                                }else{
                                    if (modifyfile('add', add_directory, [arra, treeNode.id, 1].join("|"))){
                                        addnodename=rulesfile;
                                        zTree.reAsyncChildNodes(nodes[0]);
                                    }else{
                                        layer.msg('添加失败！！！')
                                    }
                                }
                            }
                        })
                    }
                });
                return false;
            });
        }
    }

    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
    }

    // function selectAll() {
    // 	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    // 	zTree.setting.edit.editNameSelectAll =  $("#selectAll").attr("checked");
    // }

    function zTreeBeforeClick(treeId, treeNode, clickFlag) {
        return (treeNode.id !== 1);
    }

    //var click_treeNode;
    function zTreeOnClick(event, treeId, treeNode) {
        var click_treeNode = treeNode;
        var path = "";
        p = click_treeNode.getParentNode();
        while (p !== null){
            path = p.name + "\\" + path;
            p = p.getParentNode();
        }
        tree_dir_file = path +  click_treeNode.name;
        console.log(tree_dir_file)
    }

    //递归查询tree的节点
    function checkAllParents(treeNode, recursivename,treeNodename){
        if (treeNode===null || treeNode.pId===0) {
            return recursivename;
        }
        else
        {
            // treeNode.checked=true;
            if (treeNode.name === treeNodename){
                recursivename = undefined
            }
            else if (recursivename === undefined){
                recursivename = treeNode.name
            } else {
                recursivename = treeNode.name + '\\' + recursivename;
            }
            return checkAllParents(treeNode.getParentNode(), recursivename);
        }
    }

    // 查询当前节点所有子节点
    // function getAllChildrenNodes(treeNode,result){
    //     if (treeNode.isParent) {
    //         var childrenNodes = treeNode.children;
    //         if (childrenNodes) {
    //             for (var i = 0; i < childrenNodes.length; i++) {
    //                 result += ',' + childrenNodes[i].id;
    //                 result = getAllChildrenNodes(childrenNodes[i], result);
    //             }
    //         }
    //     }
    //     return result;
    // }

    //修改
    function modifyfile(mod_status, mod_old_file, mod_new_file) {
        var modify_status = true;
        $.ajax({
            url: "/rules-modify/",
            dataType: "json",
            type: "POST",
            async: false,
            data : {'type':mod_status, 'old_file':mod_old_file, 'new_file': mod_new_file},
            success: function(return_status){
                console.log('返回状态',return_status["status"]);
                if (return_status["status"] === 0){
                    console.log('执行成功')
                }else{
                    modify_status = false;
                    layer.msg('程序执行异常')
                }
            },
            error: function () {
                console.log('error');
                modify_status = false
            }
        });
        return modify_status
    }

    //tree 文件查看
    //查看按钮
    var check_file_mod;
    var check_node;
    $("#checkfile").on("click", function () {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        var nodes = zTree.getSelectedNodes();
        check_node = nodes[0];
        console.log(nodes[0]);
        if (nodes.length === 0 || nodes[0].status === 0) {
            layer.msg("请选择文件");
        }else{
            var checkdatafile = checkAllParents(nodes[0], '',nodes[0].name);

            if (checkdatafile===undefined){
                checkdatafile = nodes[0].name;
            }else{
                checkdatafile = checkdatafile + "\\" + nodes[0].name;
            }
            check_file_mod = checkdatafile;
            $.ajax({
                url: "/rules-content-check/",
                type: "POST",
                dataType: "text",
                data: {"checkfile": checkdatafile},
                success: function (checkdata) {
                    console.log("查看文件",checkdata);
                    if (checkdata === "error"){
                        layer.msg("文件格式不正确！")
                    }else{
                        var $obj = $("#filedata");
                        $obj.val(checkdata);
                        $obj.attr("disabled","disabled");
                    }
                },
                error: function (adddd) {
                    console.log(adddd);
                    layer.msg("请求失败")
                }
            })
        }
    });

    //修改按钮
    var olefiledata = "";
    $("#submitfile").on("click", function () {
        var $fbj = $("#filedata");
        if ($fbj.val() !== ""){
            $fbj.removeAttr("disabled");
            $("#submitdata").css('display', 'initial');
            $("#submitfile").css('display','none');
            $("#cancelsubmit").css('display','initial');
            olefiledata = $fbj.val();
        }else{
            layer.msg("需查看后才能修改！")
        }

    });

    //提交按钮
    $("#submitdata").on("click", function () {
        var $dbj = $("#filedata");
        if ($dbj.val() !== "error"){
            var zTree = $.fn.zTree.getZTreeObj("treeDemo");
            var on_check_node = check_node.getParentNode();
            zTree.selectNode(on_check_node);
            on_check_node.isParent = true;

            $.ajax({
                url: "/rules-content-modify/",
                type: "POST",
                dataType: "json",
                data: {"data": $dbj.val(), "file":check_file_mod},
                success: function (status) {
                    if (status["status"] === 0){
                        zTree.reAsyncChildNodes(on_check_node, "refresh", false);
                        $dbj.attr("disabled","disabled");
                        $("#submitdata").css('display', 'none');
                        $("#submitfile").css('display','initial')
                    }else{
                        layer.msg("操作失败")
                    }

                },
                error: function () {
                    layer.msg("请求失败")
                }
            })
        }else{
            layer.msg("修改内容不能为空");
            $dbj.val(olefiledata)
        }
    });
    //取消
    $("#cancelsubmit").on("click", function ( ) {
        var $cbj = $("#filedata");
        $cbj.val("");
        $cbj.attr("disabled");
        $("#submitdata").css('display', 'none');
        $("#submitfile").css('display','initial');
        $("#cancelsubmit").css('display','none');
    });

    $('.demoTable .layui-btn').on('click', function() {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});